package com.example.zzx.dovebook.bookshare.booksharepass

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.MenuItem
import android.widget.ImageView
import androidx.lifecycle.Observer
import com.amap.api.services.core.PoiItem
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeResult
import com.example.baselibrary.commonutil.ToastUtil
import com.example.baselibrary.image.GlideManager
import com.example.baselibrary.image.PhotoPicker
import com.example.baselibrary.widget.LoadingDialog
import com.example.zzx.dovebook.R
import com.example.zzx.dovebook.base.BaseActivity
import com.example.zzx.dovebook.base.ValueWrapper.TYPE_NORMAL
import com.example.zzx.dovebook.base.extensions.startLocationActivityForResult
import com.example.zzx.dovebook.base.model.BookShare
import com.example.zzx.dovebook.user.UserManager
import com.example.zzx.dovebook.utils.FileController
import com.example.zzx.dovebook.utils.LocationUtil
import kotlinx.android.synthetic.main.activity_book_share_pass.*
import kotlinx.android.synthetic.main.toolbar_common.*

class BookSharePassActivity : BaseActivity<BookSharePassViewModel>() {

    private var coverPath: String = ""

    private var location: PoiItem? = null

    private lateinit var photoPicker: PhotoPicker

    private val REQUEST_CODE_LOCATION = 3

    private var preBookShare: BookShare? = null

    private lateinit var loadingDialog: LoadingDialog

    override fun getLayoutId(): Int {
        return R.layout.activity_book_share_pass
    }

    override fun getStatusBarColor(): Int = STATUS_BAR_LIGHT

    override fun createViewModel(): Class<BookSharePassViewModel> {
        return BookSharePassViewModel::class.java
    }

    override fun createRepository(): Any {
        return BookSharePassRepository()
    }

    override fun initIntent(savedInstanceState: Bundle?) {
        preBookShare = intent.getSerializableExtra("book_share") as BookShare?
        preBookShare ?: finish()
    }

    override fun initViews(savedInstanceState: Bundle?) {
        setupToolbar()

        setupBookImg()

        setupLocationTv()

        setupSendBtn()

        loadingDialog = LoadingDialog(this)
    }

    private fun setupSendBtn() {
        sendBtn.setOnClickListener {
            passBookShare()
        }
    }

    override fun initOptions(savedInstanceState: Bundle?) {
        initLocationInfo()
    }

    private fun initLocationInfo() {
        LocationUtil.locationAndGeocode(this, object : GeocodeSearch.OnGeocodeSearchListener {
            override fun onRegeocodeSearched(regeocodeResult: RegeocodeResult, resultCode: Int) {
                val address = regeocodeResult.regeocodeAddress
                if (address.pois.size > 0) {
                    location = address.pois[0]
                    val locationDescription = "#${location!!.cityName}${location!!.adName}${location!!.title}#"
                    locationTv.text = locationDescription
                }
            }

            override fun onGeocodeSearched(geocodeResult: GeocodeResult, resultCode: Int) {

            }

        }, true)
    }

    private fun setupLocationTv() {
        locationTv.setOnClickListener {
            if (location == null) {
                startLocationActivityForResult(null, null, REQUEST_CODE_LOCATION)
            } else {
                location?.apply {
                    startLocationActivityForResult(latLonPoint, "$cityName$adName$title", REQUEST_CODE_LOCATION)

                }
            }
        }
    }

    private fun passBookShare() {
        if (TextUtils.isEmpty(coverPath)) {
            ToastUtil.shortToast(this, "请先选择一张图片")
            return
        }
        val description = descriptionEdit.editableText.toString()
        if (TextUtils.isEmpty(description)) {
            ToastUtil.shortToast(this, "写点心得吧")
            return
        }
        if (location == null) {
            ToastUtil.shortToast(this, "左下角选择地址")
            return
        }
        val userId = UserManager.getInstance(this).loginUserId ?: ""
        loadingDialog.show()
        viewModel.passBookShare(coverPath, userId, preBookShare!!.bookId, description, location!!.latLonPoint)
            .observe(this, Observer {
                loadingDialog.dismiss()
                it?.apply {
                    if (type == TYPE_NORMAL) {
                        finish()
                    }
                }
            })
    }

    private fun setupBookImg() {
        photoPicker = PhotoPicker().apply {
            compress = true
            tempPhotoPath = FileController.getTempCoverPath(this@BookSharePassActivity)
            fileProviderAuthorities = FileController.COVER_FILE_PROVIDER_AUTHORITIES
            onPickListener = PhotoPicker.OnPickListener {
                coverPath = it
                this@BookSharePassActivity.bookImg.scaleType = ImageView.ScaleType.CENTER_CROP
                GlideManager.loadImage(this@BookSharePassActivity, coverPath,
                    this@BookSharePassActivity.bookImg)

            }
        }
        bookImg.setOnClickListener {
            photoPicker.show(supportFragmentManager, photoPicker.createTag())
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            REQUEST_CODE_LOCATION -> if (resultCode == RESULT_OK) handleLocationResult(data!!)
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    private fun handleLocationResult(data: Intent) {
        location = data.getParcelableExtra("result_location")
        location?.apply {
            val locationDescription = "#$cityName$adName$title#"
            locationTv.text = locationDescription
        }
    }

    private fun setupToolbar() {
        toolbar.setTitleTextAppearance(this, R.style.BoldTitleStyle)
        toolbar.title = getString(R.string.title_activity_pass)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> finish()
        }

        return super.onOptionsItemSelected(item)
    }

}
